package com.lzk.jetpacktest.code

import android.os.CountDownTimer
import android.util.Log
import com.tencent.mmkv.MMKV

/**
 * @Author: LiaoZhongKai
 * @Date: 2021/8/17 16:38
 * @Description: 验证码倒计时工具类
 */
object CodeCountDownUtil {
    private const val KEY_TIME = "TotalTimeMills"
    private val mMkv: MMKV = MMKV.mmkvWithID("CodeCountDownUtil")
    private var mTotalTimeMills = 0L
    private var mListener: OnCountDownListener? = null

    private lateinit var mCountDownTimer: CountDownTimer

    /**
     * 开始倒计时
     * [totalTimeMills] 倒计时时间毫秒值
     */
    fun start(totalTimeMills: Long,listener: OnCountDownListener){
        mListener = listener
        mTotalTimeMills = totalTimeMills+System.currentTimeMillis()
        mMkv.encode(KEY_TIME, mTotalTimeMills)
        mCountDownTimer = object : CountDownTimer(totalTimeMills,1000) {
            override fun onTick(millisUntilFinished: Long) {
                mListener?.onTick(millisUntilFinished / 1000)
            }

            override fun onFinish() {
                mListener?.onFinish()
                reset()
            }
        }
            mCountDownTimer.start()
    }

    /**
     * 取消倒计时
     */
    fun cancel(){
        if (::mCountDownTimer.isInitialized){
            mCountDownTimer.cancel()
        }
        mListener = null
    }

    /**
     * 重置倒计时，将剩余时间置为0
     * 验证码发送失败或验证码发送成功后都需要重置
     */
    fun reset(){
        mMkv.encode(KEY_TIME,0L)
        cancel()
        mTotalTimeMills = 0L
    }

    /**
     * 获取当前的倒计时时间毫秒值
     */
    fun getCountTimeMills(): Long{
        mTotalTimeMills = mMkv.decodeLong(KEY_TIME)
        return mTotalTimeMills - System.currentTimeMillis()
    }

    /**
     * 当前时间是否在倒计时范围内
     * @return true: 倒计时正在进行 false:倒计时未进行
     */
    fun isCounting(): Boolean{
        mTotalTimeMills = mMkv.decodeLong(KEY_TIME)
        return System.currentTimeMillis() < mTotalTimeMills
    }

    interface OnCountDownListener{
        /**
         * 倒计时
         * [seconds] 倒计时剩余时间，秒为单位
         */
        fun onTick(seconds: Long)

        /**
         * 倒计时结束
         */
        fun onFinish()
    }
}